package com.cloudkinto.controller.stock;


import com.cloudkinto.bo.stock.ProductStockByLocationQueryBo;
import com.cloudkinto.bo.storage.StorageLocationQueryBo;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dto.stock.StockCheckPageDto;
import com.cloudkinto.dto.stock.StockCheckProductDetailDto;
import com.cloudkinto.dto.stock.query.SkuCellStockPageDto;
import com.cloudkinto.service.detective.vo.StartPickReq;
import com.cloudkinto.service.stock.ProductStockService;
import com.cloudkinto.service.stock.StockCheckProductService;
import com.cloudkinto.service.stock.vo.snap.*;
import com.cloudkinto.service.storage.StorageLocationService;
import com.cloudkinto.vo.storage.StorageLocationVo;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.stock.StockCheckService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.cloudkinto.base.BaseController;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author hua
 * @since 2024-12-23
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "盘点模块")
@RequestMapping("/api/admin/wms/StockCheck")
public class StockCheckWmsController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(StockCheckWmsController.class);

    private final StockCheckService service;
    private final StorageLocationService storageLocationService;
    private final ProductStockService productStockService;
    private final StockCheckProductService stockCheckProductService;


    @UserSessionRequired
    @PostMapping("/cellList")
    @ApiOperation(value = "库位盘点 添加库位按钮 ", notes = "库位表查询（分页）")
    public PageResult<StorageLocationVo> listPage(@RequestBody StorageLocationQueryBo bo) {
        bo.setWhId(getWarehouseId());
        bo.setTenantId(getTenantId(StaticDict.System_Source.WMS.getValue()));
        return storageLocationService.getListPage(bo);
    }

    @UserSessionRequired
    @PostMapping("/productListPageByLocation")
    @ApiOperation(value = "sku+库位盘点 添加产品按钮", notes = "按库位查询")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = SkuCellStockPageDto.class))
    public PageResult productListPageByLocation(@RequestBody @Validated ProductStockByLocationQueryBo req) {
        req.setTenantId(getTenantId());
        req.setWhId(getWarehouseId());
        return productStockService.productListPageByLocation(req);
    }


    @UserSessionRequired
    @GetMapping("/getProductByLocation")
    @ApiOperation(value = "根据库位 获取盘点明细", notes = "按库位查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cellCode", value = "库位编码"),
            @ApiImplicitParam(name = "cellCodes", value = "库位编码,多个逗号隔开")

    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = SkuCellStockPageDto.class))
    public SingleResult getProductByLocation(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", getTenantId());
        map.put("whId", getWarehouseId());
        map.put("cellCode", request.getParameter("cellCode"));

        String cellCodes = request.getParameter("cellCodes");
        if (StringUtils.isNotBlank(cellCodes)) {
            map.put("cellCodes", Arrays.asList(cellCodes.split(",")));
        }
//        map.put("cellCode", );

        return SingleResult.success(service.productListPageByLocation(map));
    }


    @UserSessionRequired
    @GetMapping("/start")
    @ApiOperation(value = "开始盘点", notes = "开始盘点")
    public SingleResult start(Long id) {
        service.start(id, getCurrentUserId(), getWarehouseId(), getTenantId(StaticDict.System_Source.WMS.getValue()));
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/submit")
    @ApiOperation(value = "提交", notes = "提交")
    public SingleResult submit(Long id) {
        service.submit(id, getCurrentUserId(), getWarehouseId(), getTenantId(StaticDict.System_Source.WMS.getValue()));
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/abort")
    @ApiOperation(value = "作废", notes = "作废")
    public SingleResult abort(Long id) {
        service.abort(id, getCurrentUserId(), getWarehouseId(), getTenantId(StaticDict.System_Source.WMS.getValue()));
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated StockCheckAddReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("新增成功",service.add(req,userId, getWarehouseId(), getTenantId()));
    }


    @UserSessionRequired
    @PutMapping
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated StockCheckUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功",service.update(req,userId, getWarehouseId(), getTenantId(StaticDict.System_Source.WMS.getValue())));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功",service.delete(id,userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockCheckDetailRes.class))
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功",service.detail(id, getWarehouseId(), getTenantId(StaticDict.System_Source.WMS.getValue())));
    }


    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

//    @GetMapping("/list")
//    @ApiOperation(value = "查询", notes = "查询")
//    public SingleResult list(HttpServletRequest request){
//        Long companyId = getCompanyId();
//
//        Map<String, String> map = new HashMap<>();
//        String keyword = request.getParameter("keyword");
//        map.put("keyword", keyword);
//        return SingleResult.success("查询成功", service.getList(map));
//    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "stockType", value = "库存类型"),
            @ApiImplicitParam(name = "checkType", value = "盘点类型"),
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time  等等"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "sku", value = "sku"),
            @ApiImplicitParam(name = "orderNo", value = "盘点单号"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockCheckPageDto.class))
    public PageResult listPage(HttpServletRequest request){

        Map<String, Object> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/statusStatistics")
    @ApiOperation(value = "状态数量统计", notes = "状态数量统计")
    @ApiImplicitParams({@ApiImplicitParam(name = "returnType", value = "退件类型 1平台退件 2买家退件 3服务商退件"),
            @ApiImplicitParam(name = "storageIds", value = "仓库", type = "arr"),
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time submit_time 等等"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "selectColumn", value = "查询类型 sku, fn_sku, track_no 等等"),
            @ApiImplicitParam(name = "selectValue", value = "查询值"),
            @ApiImplicitParam(name = "status", value = "状态"),
    })
    public SingleResult statusStatistics(HttpServletRequest request) {
        Map<String, Object> map = this.getMap(request);
        return SingleResult.success(service.statusStatistics(map));
    }

    public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String status = request.getParameter("status");
        String stockType = request.getParameter("stockType");
        String checkType = request.getParameter("checkType");
        String dateColumn = request.getParameter("dateColumn");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String sku = request.getParameter("sku");
        String orderNo = request.getParameter("orderNo");
        map.put("status", status);
        map.put("stockType", stockType);
        map.put("checkType", checkType);
        map.put("dateColumn", dateColumn);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("sku", sku);
        map.put("orderNo", orderNo);
        map.put("whId", getWarehouseId());
        map.put("tenantId", getTenantId(StaticDict.System_Source.WMS.getValue()));
        return map;
    }




    @UserSessionRequired
    @GetMapping("/dtlInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sku", value = "sku"),
            @ApiImplicitParam(name = "cellNo", value = "库位"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),
            @ApiImplicitParam(name = "checkId", value = "主表Id"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiOperation(value = "详情-产品信息 查询（分页）", notes = "详情-产品信息查询（分页）")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockCheckProductDetailDto.class))
    public PageResult dtlInfo(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        String checkId = request.getParameter("checkId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String sku = request.getParameter("sku");
        String cellNo = request.getParameter("cellNo");
        String productName = request.getParameter("productName");
        map.put("checkId", checkId);
        map.put("current", current);
        map.put("pageSize", size);
        map.put("sku", sku);
        map.put("cellNo", cellNo);
        map.put("productName", productName);
        return stockCheckProductService.getListPage(map);
    }



    @UserSessionRequired
    @PostMapping("/printCheckList")
    @ApiOperation(value = "打印", notes = "打印")
    public void printPick(@RequestBody @Validated StartPickReq req, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", getTenantId(StaticDict.System_Source.WMS.getValue()));
        map.put("source", "wms");
        map.put("whId", getWarehouseId());
        map.put("id", req.getId());
        service.printCheckList(map, response);
    }

}

